package com.aipodcast.webbackend.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.PrintWriter;
import java.io.StringWriter;


@Slf4j
public class ExceptionUtil {

    
    /** 
     * @author RedStar
     * @date 2025/3/7 21:52
     * @description 将异常堆栈信息格式化为字符串
     * @param e 异常对象
     * @return 格式化后的异常信息
     */
    public static String getStackTraceAsString(Throwable e) {
        if (e == null) {
            return "No exception provided.";
        }

        try (StringWriter sw = new StringWriter();
             PrintWriter pw = new PrintWriter(sw)) {
            e.printStackTrace(pw);
            pw.flush();
            return sw.toString();
        } catch (Exception ex) {
            log.error("Failed to convert stack trace to string", ex);
            return "Failed to convert stack trace to string: " + ex.getMessage();
        }
    }

    /**
     * @author RedStar
     * @date 2025/3/7 21:52
     * @description 记录异常日志（带自定义消息）
     * @param message 自定义日志消息
     * @param e       异常对象
     */
    public static void logError(String message, Throwable e) {
        if (e == null) {
            log.error(message);
            return;
        }

        String stackTrace = getStackTraceAsString(e);
        log.error("{}, error message: {}", message, stackTrace);
    }

    /**
     * @author RedStar
     * @date 2025/6/19 20:15
     * @description 控制台输出异常
     */
    public static void consoleError(String message, Throwable e) {
        if (e == null) {
            System.out.println(message);
            return;
        }
        System.out.println(formatError(message, e));
    }
    
    /**
     * @author RedStar
     * @date 2025/3/7 21:52
     * @description 记录异常日志（不带自定义消息）
     * @param e       异常对象
     */
    public static void logError(Throwable e) {
        if (e == null) {
            log.error("An error occurred, but no exception was provided.");
            return;
        }

        String stackTrace = getStackTraceAsString(e);
        log.error("An error occurred: {}", stackTrace);
    }

    /**
     * @author RedStar
     * @date 2025/3/18 20:50
     * @description 格式化错误信息
     */
    public static String formatError(String message, Throwable e) {
        return String.format("%s 错误信息: %s", message, getStackTraceAsString(e));
    }

    /**
     * @author RedStar
     * @date 2025/3/18 20:51
     * @description 格式化错误信息
     */
    public static String formatError(Throwable e) {
        return String.format("发生异常: %s", getStackTraceAsString(e));
    }
}